<template>
  <div>
    <el-button @click="loadNestedData">加载二层嵌套数据</el-button>
    <div ref="chart" style="width: 350px; height: 200px"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import moment from 'moment';
import 'moment/locale/zh-cn'
export default {
  data () {
    return {
      mycart: null
    };
  },
  methods: {
    initChart () {
      this.mycart = echarts.init(this.$refs.chart);
      this.mycart.setOption({});
    },

    loadNestedData () {
      const nestedData = [
        {
          "satellite": "Satellite A",
          "positions": [
            { "date": "2023-01-01", "altitude": 120 },
            { "date": "2023-01-02", "altitude": 200 },
            { "date": "2023-01-03", "altitude": 150 }
          ]
        },
        {
          "satellite": "Satellite B",
          "positions": [
            { "date": "2023-01-01", "altitude": 180 },
            { "date": "2023-01-02", "altitude": 220 },
            { "date": "2023-01-03", "altitude": 160 }
          ]
        }
      ];
      this.updateChart(nestedData);
    },
    updateChart (data) {
      let xData = new Set();
      let seriesData = [];
      data.forEach(satellites => {
        let yData = [];
        satellites.positions.forEach(position => {
          //moment.js 格式化日期
          const formattedDate = moment(position.date).format('YYYY/MM/DD');
          xData.add(formattedDate);
          // xData.add(position.date);
          yData.push(position.altitude);
        });
        seriesData.push({
          name: satellites.satellite,
          type: 'line',
          data: yData
        });
      })
      xData = Array.from(xData);
      this.mycart && this.mycart.setOption({
        legend: {
          scrollData: true // 启用滚动
        },
        tooltip: {
          trigger: 'axis', // 坐标轴触发
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: seriesData
      })


    }
  },
  mounted () {
    this.initChart();
  }
};
</script>

